package org.baicaixiaozhan.learncommon.config;

import org.baicaixiaozhan.learncommon.exception.UserPerceivableSpecificException;
import org.baicaixiaozhan.learncommon.util.ResultTemplate;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * DESC: 全局异常通知处理
 *
 * @author baicaixiaozhan
 * @since 2021-06-22
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {

    private static final String MESSAGE = "未知异常，请联系系统管理员。";

    @ExceptionHandler(Exception.class)
    public ResultTemplate<Object> exceptionHandler(Exception e) {
        if (isPrintStackTrace(e)) {
            e.printStackTrace();
            return ResultTemplate.internalServerError(MESSAGE);
        } else {
            return ResultTemplate.badRequest(e.getMessage());
        }
    }

    /**
     * 是否需要打印异常堆栈信息
     *
     * @param e 目标异常
     * @return 需要打印返回 true，反之，返回 false
     */
    private boolean isPrintStackTrace(Exception e) {
        return !(e instanceof UserPerceivableSpecificException);
    }
}
